﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Threading.Tasks;
using ufida.u9.ait.openapi.utils;
using UFIDA.U9.Base;
using UFIDA.U9.CBO.MFG.PMM;
using UFIDA.U9.CBO.SCM.Item;
using UFIDA.U9.ISV.SM;
using UFIDA.U9.ISV.SM.Proxy;
using UFIDA.U9.PM.PO;
using UFIDA.U9.SM.SO;
using UFIDA.U9.SM.SOModify;
using UFSoft.UBF.Business;
using UFSoft.UBF.Util.Context;
using static ufida.u9.ait.openapi.utils.ObjUtils;

namespace ufida.u9.ait.openapi
{
    internal class SOModifyBase
    {
        /// <summary>
        /// 引用集团示例方法,稍作修改
        /// 现在只支持
        /// 新增行
        /// 修改行,修改数量/单价/金额,其他不支持
        /// 关闭行
        /// </summary>
        /// <param name="sodto"></param>
        /// <returns></returns>
        private static SO CreateSOModify(SOAITDTOData sodto)
        {
            SOAITDTOData soModifyFirst = sodto;
            var org = UFIDA.U9.Base.Context.LoginOrg;
            //检查该单号是否存在
            var so = SO.Finder.Find("DocNo='" + soModifyFirst.DocNo + "'") ?? throw new Exception("销售订单" + soModifyFirst.DocNo + "不存在");

            PlatformContext context = PlatformContext.Current;
            //查询出销售订单
            UFIDA.U9.ISV.SM.Proxy.CommonQuerySOSRVProxy queryProxy = new CommonQuerySOSRVProxy();
            queryProxy.ContextDTO = new UFIDA.U9.CBO.Pub.Controller.ContextDTOData();
            queryProxy.ContextDTO.UserCode = context.UserCode;
            queryProxy.ContextDTO.EntCode = context.EnterpriseID;
            queryProxy.ContextDTO.CultureName = context.Culture;
            queryProxy.ContextDTO.OrgCode = context.OrgCode;
            queryProxy.SOs = new List<UFIDA.U9.CBO.Pub.Controller.CommonArchiveDataDTOData>();
            var data = new UFIDA.U9.CBO.Pub.Controller.CommonArchiveDataDTOData();
            data.Code = so.DocNo;
            data.ID = so.ID;
            queryProxy.SOs.Add(data);
            var querySOList = queryProxy.Do();

            var closeKeys = new List<SOLineKeyDTOData>();//SO关闭行
            var querySO = querySOList[0];
            
            //对比新SO行与旧SO行
            List<ObjUtils.OperItem> operItems = ObjUtils.CompareList(soModifyFirst.SOLines, querySO.SOLines, "DocLineNo");

            //增对每行 新增/修改/删除 单独处理
            bool isModify = false;
            foreach (var item in operItems)
            {
                if (item.oper == OperEnum.add)
                {
                    //新增行
                    SOLineAITDTOData newline = (SOLineAITDTOData)item.item1;
                    querySO.SOLines.Add(new UFIDA.U9.ISV.SM.SOLineDTOData
                    {
                        DocLineNo = newline.DocLineNo,
                        ItemInfo = new ItemInfoData
                        {
                            ItemCode = newline.ItemInfo.ItemCode,
                        },
                        PriceCalField = "FinallyPrice",
                        OrderByQtyTU = newline.OrderByQtyTU,
                        FinallyPriceTC = newline.FinallyPriceTC,
                        TotalMoneyTC = newline.TotalMoneyTC,
                        TaxSchedule = querySO.TaxSchedule,
                        SrcDocType = 0,
                        //SysState = UFSoft.UBF.PL.Engine.ObjectState.Inserted,
                    });
                    isModify = true;
                }
                else if (item.oper == OperEnum.update)
                {
                    //修改行
                    SOLineAITDTOData newline = (SOLineAITDTOData)item.item1;
                    UFIDA.U9.ISV.SM.SOLineDTOData oldline = (UFIDA.U9.ISV.SM.SOLineDTOData)item.item2;
                    if (oldline.TotalMoneyTC != newline.TotalMoneyTC)
                    {
                        //金额变更
                        oldline.PriceCalField = "TotalMoneyTC";
                        oldline.TotalMoneyTC = newline.TotalMoneyTC;
                        oldline.IsModifyTotalMoneyTC = true;
                        isModify = true;
                    }
                    if (oldline.OrderByQtyTU != newline.OrderByQtyTU)
                    {
                        //数量变更
                        oldline.PriceCalField = "FinallyPrice";
                        oldline.OrderByQtyTU = newline.OrderByQtyTU;
                        isModify = true;
                    }
                    if (oldline.FinallyPriceTC != newline.FinallyPriceTC)
                    {
                        //单价变更
                        oldline.PriceCalField = "FinallyPrice";
                        oldline.IsModifyFinallyPriceTC = true;
                        oldline.FinallyPriceTC = newline.FinallyPriceTC;
                        oldline.IsModifyOrderPriceTC = true;
                        oldline.OrderPriceTC = newline.FinallyPriceTC;
                        isModify = true;
                        //querySOLine.IsModifyFreeType = true;
                        //querySOLine.FreeType = 1;
                    }
                }
                else if (item.oper == OperEnum.delete)
                {
                    //删除行
                    UFIDA.U9.ISV.SM.SOLineDTOData oldline = (UFIDA.U9.ISV.SM.SOLineDTOData)item.item2;
                    //从变更行中去掉该行
                    querySO.SOLines.Remove(oldline);
                    SOLine soline=SOLine.Finder.FindByID(oldline.ID);
                    if (soline == null) throw new Exception("依据行ID查询SOLine失败!");
                    if (soline.Status == SODocStatusEnum.Approved)
                    {
                        //原始行状态=已审,直接关闭
                        closeKeys.Add(new SOLineKeyDTOData
                        {
                            LineKeyDTO = new UFIDA.U9.CBO.Pub.Controller.CommonArchiveDataDTOData
                            {
                                ID = oldline.ID
                            }
                        });
                    }
                }
            }

            if (isModify)
            {
                //下述参数决定是否生成变更单
                querySO.AutoCreateSOM = true;
                querySO.AutoApproveSOM = true;
                querySO.IsRollBack = true;

                //SO变更
                var proxy = new CommonModifySOSRVProxy();
                proxy.SOs = querySOList;
                proxy.Do(org.ID);
            }
            if (closeKeys.Count > 0)
            {
                //SO行关闭
                CloseSOLineSrvProxy closelineSV = new CloseSOLineSrvProxy();
                closelineSV.SOLineKeyDTOs = closeKeys;
                closelineSV.Do();
            }
            return so;
        }

        /// <summary>
        /// 依据现有SO创建SO变更单
        /// </summary>
        /// <param name="so">原SO</param>
        /// <returns>变更后SO</returns>
        public static SO CreateDoc(SOAITDTOData sodto, SO so)
        {
            CreateSOModify(sodto);

            //so = so.Key.GetEntity();
            return so;
        }

        public static SOModify ApproveDoc(SOModify doc)
        {
            doc = doc.Key.GetEntity();
            if (doc.Status != SOModifyStatusEnum.Approving)
                throw new Exception($"单号：[{doc.DocNo}]状态不为提交，不能审核！");

            SOModifyStatusModifyBP bp = new SOModifyStatusModifyBP();
            bp.SOModifyDtos = new List<UFIDA.U9.SM.SOModify.SOModifyDTO>() {
                        new UFIDA.U9.SM.SOModify.SOModifyDTO(doc.Key, doc.SysVersion, SOModifyStatusEnum.Approved)
                    };
            bp.Do();
            return doc;
        }

        public static SOModify RevocateDoc(SOModify doc)
        {
            doc = doc.Key.GetEntity();
            if (doc.Status != SOModifyStatusEnum.Approving)
                throw new Exception($"单号：[{doc.DocNo}]状态不为提交，不能收回！");

            using (ISession session = Session.Open())
            {
                doc.Status = SOModifyStatusEnum.Openend;
                session.Commit();
            }

            return doc;
        }
    }
}
